/*
 * @Author: mayijun
 * @Date: 2022-05-14 11:12:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-06-30 16:31:58
 */
//指标下拉框组件
import { defineComponent, onMounted, PropType, reactive, watch, computed } from 'vue';
import './index.scss';
import { CaretBottom, Check } from '@element-plus/icons-vue';
import API from '@/services';
import { ElDropdown, ElDropdownItem, ElDropdownMenu, ElIcon } from 'element-plus';
import { EDicType } from '@/utils/constants';

const IndexTagDropdown = defineComponent({
  name: 'IndexTagDropdown',
  components: {
    CaretBottom,
    Check
  },
  props: {
    itemData: {
      type: Object
    },
    showGroup: {
      type: Boolean as PropType<boolean>,
      default: true
    }
  },
  emits: ['selectChange', 'groupDrawerBol'],
  setup: (props, { slots, attrs, emit }) => {

    let state = reactive({
      drawerVisible: false,
      currentSelectVal: '66',
      selectOptions: [],
      combineEnums: [] as any[],
    });

    const handleItemClick = (v: any) => {
      if (v && v.value) {
        const { value } = v;
        if (value !== '-999') {
          state.currentSelectVal = value;
          emit('selectChange', v);
        } else {
          state.currentSelectVal = '';
          emit('groupDrawerBol', true);
        }
      }
    }

    /* 默认聚合方式 */
    const getAggregationList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.aggregation
          });
        if (code === 200 && Array.isArray(data)) {
          state.combineEnums = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    const currentSelectValDis = computed(() => {
      const getVal = state.selectOptions.filter(
        (item: any) => item.value === state.currentSelectVal
      );

      if (getVal && getVal.length) {
        return (getVal[0] as any).label;
      }
      return '';
    });

    watch(() => state.combineEnums, (val: any) => {
      if (val.length === 0) {
        getAggregationList();
      } else if (val && val.length) {
        const newArr =
          val.map((e: any) => {
            e['opTtype'] = '1';
            return e;
          }) || [];

        state.selectOptions = [
          ...newArr,
          { label: '添加组合', value: '-999', opTtype: '2' }
        ] as any;
      }
    }, { immediate: true });

    watch(() => props.itemData, (val) => {
      if (props.itemData && props.itemData.aggregationId) {
        state.currentSelectVal = String(props.itemData.aggregationId);
      }
    }, { immediate: true });

    return () => {
      return (
        <div class="index-tag-dropdown">
          <ElDropdown trigger="click" v-slots={{
            dropdown: () => (
              <ElDropdownMenu class="index-dropdown-menu">
                {state.selectOptions.filter((v: any) => v.opTtype === '1').map((base: any, bIdx) => (
                  <ElDropdownItem
                    key={bIdx}
                    onClick={() => handleItemClick(base)}
                  >
                    <div class={['item', base.value == state.currentSelectVal ? 'active' : '']}>
                      <span>{base.label}</span>
                      {base.value == state.currentSelectVal && (
                        <ElIcon class="icon-check">
                          <Check />
                        </ElIcon>
                      )}
                    </div>
                  </ElDropdownItem>
                ))}
                {
                  props.showGroup && state.selectOptions.filter((v: any) => v.opTtype === '2').map((comp: any, cIdx) => (
                    <ElDropdownItem
                      key={cIdx}
                      divided={cIdx === 0}
                      onClick={() => handleItemClick(comp)}
                    >
                      <div class={['item', comp.value == state.currentSelectVal ? 'active' : '']}>
                        <span>{comp.label}</span>
                        {comp.value === state.currentSelectVal && (
                          <ElIcon class="icon-check">
                            <Check />
                          </ElIcon>
                        )}
                      </div>
                    </ElDropdownItem>
                  ))}
              </ElDropdownMenu >
            )
          }}>
            <span class="el-dropdown-link">
              {currentSelectValDis.value ? currentSelectValDis.value : '请选择'}
              <ElIcon class="el-icon--right">
                <CaretBottom />
              </ElIcon>
            </span>
          </ElDropdown >
        </div >
      );
    };
  }
});

export default IndexTagDropdown;
